<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '../stores/counter'
import { ElButton, ElCard, ElInput, ElSelect, ElOption, ElTag } from 'element-plus'
import { ArrowLeft, Search, Star, Download } from '@element-plus/icons-vue'

const router = useRouter()
const { t } = useI18n()
const appStore = useAppStore()

// 响应式数据
const searchQuery = ref('')
const selectedCategory = ref('all')
const selectedRatio = ref('all')
const selectedStyle = ref('all')

// 模板数据
const allTemplates = ref([
  {
    id: '1',
    name: 'Single Photo',
    category: 'basic',
    ratio: '1:1',
    style: 'minimal',
    width: 800,
    height: 800,
    thumbnail: '/templates/1.png',
    description: '单图展示，简洁大方',
    tags: ['单图', '简约', '经典'],
    downloads: 1250,
    rating: 4.8
  },
  {
    id: '2',
    name: 'Left-Right Layout',
    category: 'basic',
    ratio: '2:1',
    style: 'minimal',
    width: 1200,
    height: 600,
    thumbnail: '/templates/2-left.png',
    description: '左右布局，适合对比展示',
    tags: ['左右', '对比', '双图'],
    downloads: 980,
    rating: 4.6
  },
  {
    id: '3',
    name: 'Top-Bottom Layout',
    category: 'basic',
    ratio: '1:2',
    style: 'minimal',
    width: 600,
    height: 1200,
    thumbnail: '/templates/2-top.png',
    description: '上下布局，适合时间线展示',
    tags: ['上下', '时间线', '竖版'],
    downloads: 1580,
    rating: 4.9
  },
  {
    id: '4',
    name: 'Grid Layout',
    category: 'social',
    ratio: '1:1',
    style: 'modern',
    width: 1080,
    height: 1080,
    thumbnail: '/templates/4-grid.png',
    description: '四宫格布局，适合多图展示',
    tags: ['四宫格', '网格', 'Instagram'],
    downloads: 2100,
    rating: 4.7
  },
  {
    id: '5',
    name: 'Story Layout',
    category: 'social',
    ratio: '9:16',
    style: 'modern',
    width: 1080,
    height: 1920,
    thumbnail: '/templates/3-story.png',
    description: '三图故事布局，适合手机浏览',
    tags: ['故事', '竖版', '手机'],
    downloads: 1750,
    rating: 4.5
  },
  {
    id: '6',
    name: 'Banner Style',
    category: 'social',
    ratio: '16:9',
    style: 'modern',
    width: 1920,
    height: 1080,
    thumbnail: '/templates/banner.png',
    description: '横幅样式，适合封面和横幅',
    tags: ['横幅', '封面', '宽屏'],
    downloads: 890,
    rating: 4.4
  },
  {
    id: '7',
    name: 'Artistic Collage',
    category: 'creative',
    ratio: '1:1',
    style: 'artistic',
    width: 800,
    height: 800,
    thumbnail: '/templates/collage.png',
    description: '艺术拼贴风格，创意十足',
    tags: ['艺术', '创意', '拼贴'],
    downloads: 1320,
    rating: 4.8
  },
  {
    id: '8',
    name: 'Vintage Style',
    category: 'creative',
    ratio: '4:3',
    style: 'vintage',
    width: 800,
    height: 600,
    thumbnail: '/templates/vintage.png',
    description: '复古风格布局，怀旧感十足',
    tags: ['复古', '怀旧', '胶片'],
    downloads: 1150,
    rating: 4.6
  },

])

// 计算属性
const filteredTemplates = computed(() => {
  let filtered = allTemplates.value

  // 根据模式过滤
  if (!appStore.isProfessionalMode) {
    filtered = filtered.filter(t => t.category === 'basic' || t.category === 'social')
  }

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(t => 
      t.name.toLowerCase().includes(query) ||
      t.description.toLowerCase().includes(query) ||
      t.tags.some(tag => tag.toLowerCase().includes(query))
    )
  }

  // 分类过滤
  if (selectedCategory.value !== 'all') {
    filtered = filtered.filter(t => t.category === selectedCategory.value)
  }

  // 比例过滤
  if (selectedRatio.value !== 'all') {
    filtered = filtered.filter(t => t.ratio === selectedRatio.value)
  }

  // 风格过滤
  if (selectedStyle.value !== 'all') {
    filtered = filtered.filter(t => t.style === selectedStyle.value)
  }

  return filtered
})

const categories = computed(() => {
  const cats = [
    { value: 'all', label: t('templates.all') },
    { value: 'basic', label: t('templates.basic') },
    { value: 'social', label: t('templates.social') }
  ]

  if (appStore.isProfessionalMode) {
    cats.push({ value: 'creative', label: t('templates.creative') })
  }

  return cats
})

// 方法
function goBack() {
  router.push('/')
}

function useTemplate(template: any) {
  router.push(`/editor?template=${template.id}`)
}

function downloadTemplate(template: any) {
  console.log('Download template:', template.id)
}

function formatDownloads(count: number) {
  if (count >= 1000) {
    return (count / 1000).toFixed(1) + 'k'
  }
  return count.toString()
}

function handleImageError(event: Event) {
  const target = event.target as HTMLImageElement
  if (target) {
    target.style.display = 'none'
  }
}
</script>

<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900">
    <!-- 顶部导航 -->
    <header class="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-4">
      <div class="max-w-7xl mx-auto flex items-center justify-between">
        <div class="flex items-center space-x-4">
          <ElButton @click="goBack" circle>
            <ArrowLeft />
          </ElButton>
          <h1 class="text-xl font-semibold text-gray-900 dark:text-white">{{ t('templates.title') }}</h1>
        </div>
        
        <div class="flex items-center space-x-4">
          <ElInput
            v-model="searchQuery"
            :placeholder="t('templates.search')"
            class="w-64"
            clearable
          >
            <template #prefix>
              <Search />
            </template>
          </ElInput>
        </div>
      </div>
    </header>

    <div class="max-w-7xl mx-auto px-4 py-6">
      <!-- 筛选工具栏 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg p-4 mb-6 shadow-sm">
        <div class="flex flex-wrap items-center gap-4">
          <div class="flex items-center space-x-2">
            <span class="text-sm font-medium text-gray-700 dark:text-gray-300">{{ t('templates.category') }}:</span>
            <ElSelect v-model="selectedCategory" class="w-32">
              <ElOption 
                v-for="cat in categories" 
                :key="cat.value" 
                :label="cat.label" 
                :value="cat.value" 
              />
            </ElSelect>
          </div>
          
          <div class="flex items-center space-x-2">
            <span class="text-sm font-medium text-gray-700 dark:text-gray-300">{{ t('templates.ratio') }}:</span>
            <ElSelect v-model="selectedRatio" class="w-24">
              <ElOption :label="t('templates.all')" value="all" />
              <ElOption label="1:1" value="1:1" />
              <ElOption label="4:3" value="4:3" />
              <ElOption label="3:1" value="3:1" />
              <ElOption label="16:9" value="16:9" />
              <ElOption label="9:16" value="9:16" />
            </ElSelect>
          </div>
          
          <div class="flex items-center space-x-2">
            <span class="text-sm font-medium text-gray-700 dark:text-gray-300">{{ t('templates.style') }}:</span>
            <ElSelect v-model="selectedStyle" class="w-32">
              <ElOption :label="t('templates.all')" value="all" />
              <ElOption :label="t('templates.minimal')" value="minimal" />
              <ElOption :label="t('templates.modern')" value="modern" />
              <ElOption :label="t('templates.artistic')" value="artistic" />
              <ElOption :label="t('templates.vintage')" value="vintage" />
            </ElSelect>
          </div>
          
          <div class="ml-auto text-sm text-gray-500 dark:text-gray-400">
            {{ t('templates.all') === 'All' ? `${filteredTemplates.length} templates total` : `共 ${filteredTemplates.length} 个模板` }}
          </div>
        </div>
      </div>

      <!-- 模板网格 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        <ElCard 
          v-for="template in filteredTemplates" 
          :key="template.id"
          class="card-hover cursor-pointer"
          shadow="hover"
        >
          <!-- 模板预览图 -->
          <div class="aspect-square bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden mb-3 relative group">
            <img
              v-if="template.thumbnail"
              :src="template.thumbnail"
              :alt="template.name"
              class="w-full h-full object-cover"
              @error="handleImageError"
            />
            <div
              v-else
              class="w-full h-full bg-gradient-to-br from-blue-100 to-purple-100 dark:from-gray-600 dark:to-gray-500 flex items-center justify-center"
            >
              <span class="text-gray-500 dark:text-gray-300 text-sm">{{ template.ratio }}</span>
            </div>
            
            <!-- 悬停操作按钮 -->
            <div class="absolute inset-0 bg-black bg-opacity-50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center space-x-2">
              <ElButton @click="useTemplate(template)" type="primary" size="small">
                {{ t('templates.useTemplate') }}
              </ElButton>
              <ElButton @click="downloadTemplate(template)" size="small">
                <Download />
              </ElButton>
            </div>
          </div>
          
          <!-- 模板信息 -->
          <div class="space-y-2">
            <div class="flex items-center justify-between">
              <h3 class="font-medium text-gray-900 dark:text-white">{{ template.name }}</h3>
              <div class="flex items-center space-x-1 text-yellow-500">
                <Star class="w-4 h-4" />
                <span class="text-sm">{{ template.rating }}</span>
              </div>
            </div>
            
            <p class="text-sm text-gray-600 dark:text-gray-300 line-clamp-2">
              {{ template.description }}
            </p>
            
            <div class="flex flex-wrap gap-1">
              <ElTag 
                v-for="tag in template.tags.slice(0, 3)" 
                :key="tag" 
                size="small"
                type="info"
              >
                {{ tag }}
              </ElTag>
            </div>
            
            <div class="flex items-center justify-between text-sm text-gray-500 dark:text-gray-400">
              <span>{{ template.width }}×{{ template.height }}</span>
              <span>{{ formatDownloads(template.downloads) }} {{ t('templates.downloads') }}</span>
            </div>
          </div>
        </ElCard>
      </div>
      
      <!-- 空状态 -->
      <div v-if="filteredTemplates.length === 0" class="text-center py-16">
        <div class="text-gray-400 text-6xl mb-4">🔍</div>
        <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-2">{{ t('templates.noResults') }}</h3>
        <p class="text-gray-600 dark:text-gray-300">{{ t('templates.adjustFilters') }}</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.card-hover {
  transition: all 0.3s ease;
}

.card-hover:hover {
  transform: translateY(-4px);
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
